package com.cimu.mybatisplus2.config;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * 注入公共字段自动填充,任选注入方式即可
 */
public class SolarMetaObjectHandler extends MetaObjectHandler {

    protected final static Logger logger = LoggerFactory.getLogger(SolarMetaObjectHandler.class);
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("新增的时候干点不可描述的事情");
        Date now = new Date();
        Object createTimeObj = getFieldValByName(CREATE_TIME, metaObject);
        if (null == createTimeObj) {
            setFieldValByName(CREATE_TIME, now, metaObject);
        }
        preUpdate(metaObject, now);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        logger.info("更新的时候干点不可描述的事情");
        Date now = new Date();
        preUpdate(metaObject, now);
    }

    /**
     * 封装更新的统一处理
     *
     * @param metaObject MetaObject
     * @param now        Date
     */
    private void preUpdate(MetaObject metaObject, Date now) {
        //强制维护时间
        setFieldValByName(UPDATE_TIME, now, metaObject);
    }

}
